import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/alger_api_service.dart';
import '../utils/util.dart';
import 'alger_artist_detail_screen.dart';

class AlgerArtistsScreen extends StatefulWidget {
  const AlgerArtistsScreen({super.key});

  @override
  State<AlgerArtistsScreen> createState() => _AlgerArtistsScreenState();
}

class _AlgerArtistsScreenState extends State<AlgerArtistsScreen> {
  final AlgerApiService _api = AlgerApiService();
  List<AlgerArtist> _artists = [];
  bool _loading = true;
  int _offset = 0;
  static const int _limit = 30000;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadArtists();
  }

  Future<void> _loadArtists() async {
    setState(() => _loading = true);
    try {
      final list = await _api.fetchTopArtists(limit: _limit, offset: _offset);
      if (mounted) {
        setState(() {
          _artists = [..._artists, ...list];
          _offset += list.length;
          _hasMore = list.length >= _limit;
        });
      }
    } catch (e) {
      debugPrint('加载热门艺人失败: $e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _loadMore() async {
    await _loadArtists();
  }

  @override
  Widget build(BuildContext context) {
    final isWide = CommonUtils.isWideScreen(context);
    final crossAxisCount = isWide ? 6 : 3;
    final spacing = 12.0;
    final topArtists = _artists.length > 6 ? _artists.take(6).toList() : _artists.toList();
    final restArtists = _artists.length > 6 ? _artists.skip(6).toList() : <AlgerArtist>[];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
          child: Row(
            children: const [
              Text('热门艺人', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            ],
          ),
        ),
        _loading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 前6位头像网格
                  GridView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: crossAxisCount,
                      crossAxisSpacing: spacing,
                      mainAxisSpacing: spacing,
                      childAspectRatio: 0.78,
                    ),
                    itemCount: topArtists.length,
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      final a = topArtists[index];
                      return GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) => AlgerArtistDetailScreen(
                                artistId: a.id,
                                artistName: a.name,
                                picUrl: a.picUrl,
                              ),
                            ),
                          );
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(10),
                              child: AspectRatio(
                                aspectRatio: 1,
                                child: CachedNetworkImage(
                                  imageUrl: a.picUrl,
                                  fit: BoxFit.cover,
                                  // 限制缓存尺寸，减少内存与磁盘占用
                                  memCacheWidth: 200,
                                  memCacheHeight: 200,
                                  maxWidthDiskCache: 200,
                                  maxHeightDiskCache: 200,
                                  placeholder: (context, url) => Container(
                                    color: Colors.grey[200],
                                  ),
                                  errorWidget: (context, url, error) => Container(
                                    color: Colors.grey[300],
                                    child: const Icon(Icons.broken_image, size: 20),
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(height: 6),
                            Text(
                              a.name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(fontSize: 12),
                            ),
                          ],
                        ),
                      );
                    },
                  ),

                  // 更多艺人仅显示名称标签
                  if (restArtists.isNotEmpty) ...[
                    const Padding(
                      padding: EdgeInsets.fromLTRB(16, 4, 16, 4),
                      child: Text(
                        '更多艺人',
                        style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Wrap(
                        spacing: 12,
                        runSpacing: 8,
                        children: [
                          for (final a in restArtists)
                            InkWell(
                              borderRadius: BorderRadius.circular(6),
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (_) => AlgerArtistDetailScreen(
                                      artistId: a.id,
                                      artistName: a.name,
                                      picUrl: a.picUrl,
                                    ),
                                  ),
                                );
                              },
                              child: Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                                child: Text(
                                  a.name,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Theme.of(context).colorScheme.onSurface.withOpacity(0.85),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ],
                ],
              ),
      ],
    );
  }
}
